package com.bwbear.test.demo;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import pojo.RpcRequest;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
@Component
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware  {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest request = (RpcRequest)msg;
        Class<?> aClass = Class.forName(request.getClassName());
        Object bean = applicationContext.getBean(aClass);
        Method method = aClass.getMethod(request.getMethodName(), request.getParameterTypes());
        Object invoke = method.invoke(bean, request.getParameters());
        ctx.writeAndFlush(invoke);
    }


}
